

use tide::{response, error::ResultExt, Context, EndpointResult};

use mongodb::db::{ThreadedDatabase, Database};

use crate::common::Response;

use bson;


#[derive(Serialize, Deserialize, Clone)]
struct Message {
    title: String,
    contents: String,
}

#[allow(dead_code)]
async fn new_message(mut ctx: Context<Database>) -> EndpointResult {
    let message = ctx.body_json().await.client_err()?;
    let doc = bson::to_bson(&message).unwrap();
    if let bson::Bson::Document(document) = doc {
        ctx.state().collection("doc").insert_one(document, None).unwrap();
    }
    Ok(response::json(Response::<()>::ok()))
}

#[allow(dead_code)]
async fn get_message(ctx: Context<Database>) -> EndpointResult {
    let id: String = ctx.param("id").client_err()?;

    let doc = doc!{
        "title": id
    };
    let mut cursor = ctx.state().collection("doc").find(Some(doc.clone()), None).ok().expect("Failed to execute find.");
    match cursor.next() {
        Some(Ok(doc)) => {
            let message = Message{
                title: doc.get("title").unwrap().to_string(),
                contents: doc.get("contents").unwrap().to_string(),
            };
            Ok(response::json(Response::ok().data(message)))
        }
        _ => Ok(response::json(Response::<()>::error(101).message("Not found".to_owned())))
    }
}

#[test]
fn main() {
    use tide::App;
    use mongodb::{Client, ThreadedClient};

    let client = Client::connect("172.20.224.81", 27017)
        .expect("Failed to initialize standalone client.");

    let db = client.db("easydoc");
    let mut app = App::with_state(db);

    app.at("/message").post(new_message);
    app.at("/message/{}").get(get_message);

    app.run("0.0.0.0:8020").unwrap();
}